//处理参数对象
const setParams = params => {
  let queryArr = []
  for (let key in params) {
    let str = key + '=' + params[key]
    queryArr.push(str)
  }
  return queryArr.join('&')
}

const wangAjax = option => {
  return new Promise((resolve, reject) => {
    // 创建xhr
    const xhr = new XMLHttpRequest()

    // 对数据进行处理
    const str = setParams(option.data)

    // 判断请求方式
    if (option.method.toUpperCase() === 'GET') {
      xhr.open('GET', str ? option.url + '?' + str : option.url)
      xhr.send()
    } else if (option.method.toUpperCase() === 'POST') {
      xhr.open('POST', option.url)
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      xhr.send(str)
    }
    // 监听
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          reject(xhr.status)
        }
      }
    }
  })
}
